package site.jlopen.service.imp;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;

import lombok.extern.slf4j.Slf4j;
import site.jlopen.entity.quartz.KusciaJobDataMap;
import site.jlopen.service.intf.quartz.QuartzService;

@Service
@Slf4j
public class QuartzServiceImpl implements QuartzService {

	@Autowired
	private Scheduler scheduler;

	private static final String DEFAULT_JOB_GROUP = "kuscia_job_group";

	private static final String DEFAULT_TRIGGER_GROUP = "kuscia_trigger_group";

	private static final String TRIGGER_PRE = "Trigger_";

	@Override
	public boolean startKusciaJobListen(Long jobId, String jobName, KusciaJobDataMap dataMap) {
		try {
			// 当前任务不存在才进行添加
			JobKey jobKey = JobKey.jobKey(String.valueOf(jobId), DEFAULT_JOB_GROUP);
			if (scheduler.checkExists(jobKey)) {
				log.info("[添加定时任务]已存在该作业，jobkey为：{}", jobKey);
				return false;
			}
			if(null == dataMap) {
				dataMap = new KusciaJobDataMap();
			}
			// 构建 Job
			JobDetail job = JobBuilder.newJob(site.jlopen.service.quartzTrigger.KusciaJobTrigger.class)
					.withIdentity(jobKey).withDescription(jobName).usingJobData("DATA", JSON.toJSONString(dataMap)).build();
			// cron表达式定时构造器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/3 * * * * ?");
			// 构建 Trigger
			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + jobName, DEFAULT_TRIGGER_GROUP))
					.withSchedule(cronScheduleBuilder).build();
			// 启动调度器
			scheduler.scheduleJob(job, trigger);
			scheduler.start();
			return true;
		} catch (Exception e) {
			log.error("[新增定时任务]失败，报错：", e);
			return false;
		}

	}

	@Override
	public String addCronJob(String jobName, String cron, String jobClassName) {
		try {
			// 当前任务不存在才进行添加
			JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
			if (scheduler.checkExists(jobKey)) {
				log.info("[添加定时任务]已存在该作业，jobkey为：{}", jobKey);
				return "已存在该作业";
			}

			// 构建 Job
			JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobKey).build();

			// cron表达式定时构造器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);

			// 构建 Trigger
			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + jobName, DEFAULT_TRIGGER_GROUP))
//                .startAt(DateUtil.parseDate(start))
//                .endAt(DateUtil.parseDate(end))
					.withSchedule(cronScheduleBuilder).build();

			// 启动调度器
			scheduler.scheduleJob(job, trigger);
			scheduler.start();
			return "SUCCESS";
		} catch (Exception e) {
			log.error("[新增定时任务]失败，报错：", e);
			return "FAIL";
		}

	}

	@Override
	public String deleteCronJob(String jobName, String jobGroup, String triggerName, String triggerGroup) {
		try {

			JobKey jobKey = JobKey.jobKey(jobName, jobGroup);

			TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroup);

			Trigger trigger = scheduler.getTrigger(triggerKey);

			if (null == trigger) {
				log.info("[停止定时任务]根据triggerName:{}和triggerGroup:{}未查询到相应的trigger！");
				return "SUCCESS";
			}
			// 暂停触发器
			scheduler.pauseTrigger(triggerKey);
			// 移除触发器
			scheduler.unscheduleJob(triggerKey);
			// 删除任务
			scheduler.deleteJob(jobKey);

			log.info("[停止定时任务]jobName:{},jobGroup:{}, triggerName:{}, triggerGroup:{},停止--------------", jobName,
					jobGroup, triggerName, triggerGroup);

			return "SUCCESS";

		} catch (SchedulerException e) {
			log.error("[停止定时任务]失败，报错：", e);
			return "FAIL";
		}
	}

	public static Job getClass(String className) throws Exception {
		Class<?> classTemp = Class.forName(className);
		return (Job) classTemp.getDeclaredConstructor().newInstance();
	}

	@Override
	public String executeImmediately(String jobName, String jobClassName) {
		try {
			JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
			JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobKey).build();

			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + jobName, DEFAULT_TRIGGER_GROUP)).build();

			// 启动调度器
			scheduler.scheduleJob(job, trigger);
			scheduler.start();
			return "SUCCESS";
		} catch (Exception e) {
			log.error("[立即执行一次任务，不定时]失败，报错：", e);
			return "FAIL";
		}
	}
}